package a04_字符串;

/**
 * <p>
 * a02_反转字符串2
 * </p>
 *
 * @author flyduck
 * @since 2024-07-09
 */
public class a02_反转字符串2 {
    public static void main(String[] args) {
        reverseStr("abcdefg", 2);
    }
    public static String reverseStr(String source, int k) {
        //k=3
        //i = 0
        //i = 6
        char[] chars = source.toCharArray();
        for (int i = 0; i < chars.length; i = i + 2 * k) {
            if(i + k - 1 < chars.length){
                swapArray(chars, i, i + k - 1);
            }else {
                swapArray(chars, i, chars.length - 1);
            }
        }
        return new String(chars);
    }


    private static void swapArray(char[] chars,int leftIndex,int rightIndex){
        while (leftIndex < rightIndex){
            char temp = chars[leftIndex];
            chars[leftIndex] = chars[rightIndex];
            chars[rightIndex] = temp;
            leftIndex++;
            rightIndex--;
        }
    }
}
